package com.service;

import com.mapper.UserMapper;
import com.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RenewRedisLock renewRedisLock;

    public void add(User user) {
        userMapper.insert(user);
    }

    public int updateBySynchronized(Integer id) {
        synchronized (this) {
            User user = userMapper.selectById(id);
            user.setAge(user.getAge() + 1);
            return userMapper.updateById(user);
        }
    }

    public int update(User user) throws InterruptedException {
        Integer id = user.getId();
        String key = id + "";
        String value = user.getName() + "";

        Boolean isLock = stringRedisTemplate.opsForValue().setIfAbsent(key, value, 30, TimeUnit.SECONDS);

        renewRedisLock.renewRedisLock(key, value, 30);

        TimeUnit.SECONDS.sleep(10);

        if (isLock) {
            User userNew = userMapper.selectById(id);
            userNew.setAge(userNew.getAge() + 1);
            int result = userMapper.updateById(userNew);

            String inRedisName = stringRedisTemplate.opsForValue().get(key);
            if (!StringUtils.isEmpty(inRedisName) && inRedisName.equals(value)) {
                stringRedisTemplate.delete(key);
            }

            return result;
        } else {
            return 0;
        }

    }


}
